/**
 * %分片组件%
 * %版本信息%
 */
package com.leehom.arch.base.shard.service;

import java.util.Date;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.leehom.arch.base.shard.model.Shard;
import com.leehom.arch.base.shard.model.ShardId;
import com.leehom.arch.base.shard.repository.ShardRepository;

/**
 * @类名: ShardingService
 * @说明: 分片服务
 * 
 * @author leehom
 * @Date 2012-6-16 下午10:41:35
 * @修改记录：
 * 
 * @see
 * 
 * TODO
 *   *. 分片策略，按需(延时)分片，可变分片大小
 *   
 */
@Service
public class ShardingService {
	
	@Autowired
	private ShardRepository shardRepository;
	
	/**
	 * @说明：新建分片
	 *
	 * @author leehom
	 * @param shard
	 * @return
	 * 
	 */
	public Shard newShard(Shard shard) {
		shardRepository.save(shard);
		return shard;
	}

	/**
	 * @说明：获取分片
	 *
	 * @author leehom
	 * @param owner  
	 * @param resource
	 * @return
	 * 
	 */
	public Shard getShard(String owner, String resource) {
		return shardRepository.getOne(new ShardId(owner, resource));
	}

	/**
	 * @说明：删除分片
	 *
	 * @author leehom
	 * @param owner
	 * @param resource
	 * @return
	 * 
	 */
	public void removeShard(String owner, String resource) {
		shardRepository.deleteById(new ShardId(owner, resource));
	}
	
	/**
	 * @说明：更新标记
	 *
	 * @author leehom
	 * @param owner
	 * @param resource
	 * @param value
	 * 
	 */
	@Transactional
	public void updateMarker(ShardId shardId, Object value) {		
		this.updateMarker(shardId.getOwner(), shardId.getResource(), value);
		
		
	}
	
	@Transactional
	public void updateMarker(String owner, String resource, Object value) {
		// maxV instanceof Long
		if (value instanceof Long) {
			Long N = (Long)value;
			shardRepository.updateMarker(owner, resource, N);
		}		
		else // && maxV instanceof Date
		if (value instanceof Date) {
			Date D = (Date)value;
			shardRepository.updateMarker(owner, resource, D);
		}
		else if (value instanceof String) {
			String S = (String)value;
			shardRepository.updateMarker(owner, resource, S);
		}
		

	}

}
